var username,secretkey;

var carouseid;
let infoList='<option value="0" selected="selected">请选择</option>';
layui.config({
}).use(['form','laydate', 'layer', 'element','upload'],function(){
	form = layui.form;
	layer = layui.layer;
	$ = layui.jquery;
    laydate = layui.laydate;//日期
    upload = layui.upload;//上传
    element = layui.element; //元素操作
	carouseid = GetQueryString("carouseid");	//广告ID
	ChangeChooseInfo();
	if(!isNotNull(carouseid)){
		carouseid = 0;
		$("#title_name").html("添加轮播图");
	}else{
		$("#title_name").html("修改轮播图");
		initdatas();
	}
	form.on('select(ChooseProInfo)', function(data){
		ChooseProInfo();
	});
	form.on('select(ChooseProInfos)', function(data){
		ChooseProInfos();
	});
	//普通图片上传
    var uploadInst = upload.render({
		elem: '#uploadimgs'
		,url: httpurl+'/uploadImgQiniu?pathName=advert&divisor=0&dividend=5'
		,before: function(obj){
			var index = top.layer.msg('上传中，请稍候',{icon: 16,time:false,shade:0.8});
		  //预读本地文件示例，不支持ie8
		  obj.preview(function(index, file, result){
			$("#divpreview").css("display","block");
			$('#preview').attr('src', result); //图片链接（base64）
		  });
		},done: function(res){
			 // console.log(JSON.stringify(res)+"=======done");
          top.layer.closeAll();	 //关闭所有
			if(res.rtnCode==500){//如果上传失败
				$("#divpreview").css("display","none");
				$('#preview').attr('src', ""); //图片链接（base64）
				return layer.msg(res.msg);
			}
            $("#preview").attr("name",res.msg);

		}
		,error: function(err){
		  //演示失败状态，并实现重传
			var demoText = $('#demoText');
			demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn  demo-reload">重试</a>');
			demoText.find('.demo-reload').on('click', function(){
			uploadInst.upload();
		  });
		}
	 });
});
//查看广告详情
function initdatas(){
	//加载
	var index = top.layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
	$.ajax({
		url: httpurl+"/findCarouseById",
		cache: false,
		data: {
			"carouseid":carouseid
		},
		headers: {
			"Access-Control-Allow-Origin": "*",
			"Access-Control-Allow-Methods": "*",
			"Access-Control-Allow-Headers": "Authorization",
			"Authorization": GetTokenInfo()
		},
		contentType : 'application/json',
		// dataType: "json",
		success: function(data) {
			// console.log("查看广告详情====="+JSON.stringify(data));
			top.layer.closeAll();	 //关闭所有
			var dataList=data.data.CarouseInfo;
			$("#adv_position option[value="+dataList.type+"]").attr("selected",true);
			if(!(dataList.picurl=="")){
				$("#preview").attr("src",visitimgurl+"/"+dataList.picurl);
				$("#preview").attr("name",dataList.picurl);
				$("#divpreview").show();
			}
			let infos=dataList.target;
			let adv_url=infos.indexOf("?")>-1?infos.split("?")[0]:infos;
			$("#targetUrl").val(adv_url);
			if(infos!=adv_url){
				let parinfo=infos.split("?")[1];
				$("#para").val(parinfo.split("=")[0]);
				$("#right").val(parinfo.split("=")[1]);
			}
			$("#name").val(dataList.name);
			$("#stort").val(dataList.sort);
		}
	});
}

//添加或修改
function add_adv(){
	var selectid=$("#adv_position option:selected").val();
	if(selectid==-1){
		layer.msg("请选择轮播位置！",{icon:2});
		return;
	}
	var imgs=$("#preview").attr("name");
	if(!isNotNull(imgs)){
		layer.msg("请选择轮播图片！",{icon:2});
		return;
	}
	var targetUrl=$("#targetUrl").val();
	if((targetUrl=="")&&(selectid==4)){
		layer.msg("请输入跳转链接！",{icon:2});
		return;
	}
	let para=$("#para").val();
	let right=$("#right").val();
  	let name=$("#name").val();
    if(name==""){
		layer.msg("请输入标题名称！",{icon:2});
		return;
	}
	if(para!=""){
		targetUrl=targetUrl+"?"+para;
		if(right!=""){
			targetUrl=targetUrl+"="+right;
		}
	}
	var stort=$("#stort").val();
	if(stort==""){
		stort=0;
	}
    top.layer.confirm('是否确认提交吗？',{icon: 3,title:'提示信息'},function(index){
		var index = top.layer.msg('提交中，请稍候',{icon: 16,time:false,shade:0.8});
		setTimeout(function(){
			var ajaxurl="/UpdateCarouseById";
			if(carouseid==0){
				ajaxurl="/InsertCarouse";
			}
			$.ajax({
				type:"POST",
				url: httpurl+ajaxurl,
				cache: false,
				data: JSON.stringify({
					"id":carouseid,
					"type":selectid,
					"picurl":imgs,
					"target":targetUrl,
					"sort":stort,
                  	"name":name,
				}),
				dataType: "json",
				headers: {
					"Access-Control-Allow-Origin": "*",
					"Access-Control-Allow-Methods": "*",
					"Access-Control-Allow-Headers": "Authorization",
					"Authorization": GetTokenInfo()
				},
				contentType : 'application/json',
				success: function(data) {
					top.layer.closeAll();	 //关闭所有
                  if(data.rtnCode==200){
                    top.layer.msg("修改成功!!");
					re();
                  }else{
                  	top.layer.msg("修改失败，请稍后再试!");
                  }

				},error:function (res) {
					top.layer.msg("修改失败，请稍后再试!");
				}
			});
		},1000);
	})
}
//返回
function re(){
	window.location.href="CarouseList.html";
}

function ChooseProInfo() {
	var selectid=$("#left option:selected").val();
	ProductListByTypeIds(selectid);
}
//根据类型查询商品
function ProductListByTypeIds(protid) {
	$.ajax({
		url: httpurl+"/ProductListByTypeId",
		cache: false,
      	async:false,
		headers: {
			"Access-Control-Allow-Origin": "*",
			"Access-Control-Allow-Methods": "*",
			"Access-Control-Allow-Headers": "Authorization",
			"Authorization": GetTokenInfo()
		},
		contentType : 'application/json',
		data: {
			"proIdList":protid
		},
		success: function(data) {
			infoList="";
			var dataInfo=data.data;
			if(dataInfo.length>0){
				infoList='<option value="0" selected="selected">请选择</option>';
				for(let i=0;i<dataInfo.length;i++){
					infoList+='<option value="'+dataInfo[i].id+'">'+dataInfo[i].title+'</option>';
				}
				$("#prolist").html(infoList);
              	form.render();
				$("#prolist").show();

			}
		}
	});
}
function ChooseProInfos() {
	var pid=$("#prolist option:selected").val();
	$("#right").val(pid);
}



function ChangeChooseInfo(){//根据商品或者根据类型查找商品
	let type=$("#types option:selected").val();
	//清空框里面的数据
	$("#left").html("");
	$("#right").html("");
	$.ajax({
		url: httpurl+"/CarouseChangeChooseInfo",
		cache: false,
		data: {
			"types":type
		},
		headers: {
			"Access-Control-Allow-Origin": "*",
			"Access-Control-Allow-Methods": "*",
			"Access-Control-Allow-Headers": "Authorization",
			"Authorization": GetTokenInfo()
		},
		contentType : 'application/json',
		success: function(data) {
			// console.log(JSON.stringify(data)+"=====type="+type);
			if(data.rtnCode==200){
				let dataInfo=data.data;
				if(type==0){//类型
					HandleData(dataInfo);
					$("#left").show();
					$("#prolist").hide();
				}else{//商品
					HandleDatas(dataInfo);
					$("#left").hide();
					$("#prolist").show();
				}
			}

		}
	});
}

function HandleData(dataInfo) {//处理类型列表信息
	infoList='<option value="0">请选择</option>';
	for(let i=0;i<dataInfo.length;i++){
		infoList+='<option value="'+dataInfo[i].id+'">'+dataInfo[i].name+'</option>';
	}
	$("#left").html(infoList);
  form.render();
	infoList="";
}

function HandleDatas(dataInfo) {//处理商品列表信息
	infoList='<option value="0">请选择</option>';
	for(let i=0;i<dataInfo.length;i++){
		infoList+='<option value="'+dataInfo[i].productEntity.id+'">'+dataInfo[i].productEntity.title+'</option>';
	}
	$("#prolist").html(infoList);
  form.render();
	$("#let").hide();
	infoList="";
}
